package com.jshop.admin.sys.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jshop.admin.sys.entity.SysUserEntity;
import com.jshop.admin.sys.service.SysUserRoleService;
import com.jshop.admin.sys.service.SysUserService;
import com.jshop.common.constant.AdminConstant;
import com.jshop.common.exception.ApiRRException;
import com.jshop.common.result.CommonResult;
import com.jshop.common.utils.AddGroup;
import com.jshop.common.utils.Query;
import com.jshop.common.utils.ShiroUtils;
import com.jshop.common.utils.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

//import sun.jvm.hotspot.opto.HaltNode;

/**
 * 系统用户
 */
@Api(tags = "系统用户(商户)")
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    public CommonResult list(@RequestParam Map<String, Object> params) {
        //只有超级管理员，才能查看所有管理员列表
//        if (getUserId() != AdminConstant.SUPER_ADMIN) {
//            params.put("createUserId", getUserId());
//        }
        QueryWrapper queryWrapper=new QueryWrapper();
        Object keyword = params.get("keyword");
        if (keyword!=null&&keyword!="") {
            queryWrapper.like("username",keyword);
            queryWrapper.or();
            queryWrapper.like("mobile",keyword);
        }
        //查询列表数据
        Page page = new Query(params).getPage();
        IPage page1 = sysUserService.page(page,queryWrapper);
        return CommonResult.successData(page1);
    }

    /**
     * 修改登录用户密码
     */
    @ApiOperation(value = "修改密码")
    @PostMapping("/password")
    public CommonResult password(String password, String newPassword) {
        if (newPassword == null) {
            throw new ApiRRException("新密码不为能空！");
        }
        //sha256加密
        password = DigestUtil.md5Hex(password);
        //sha256加密
        newPassword = DigestUtil.md5Hex(newPassword);

        //更新密码
        int count = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (count == 0) {
            return CommonResult.failed("原密码不正确");
        }

        //退出
        ShiroUtils.logout();

        return CommonResult.successMsg("ok");
    }

    /**
     * 用户信息
     */
    @ApiOperation(value = "用户信息")
    @GetMapping("/getinfo/{userId}")
//    @RequiresPermissions("sys:user:info")
    public CommonResult<SysUserEntity> info(@PathVariable("userId") Integer userId) {
        SysUserEntity user = sysUserService.queryObject(userId);

        //获取用户所属的角色列表
        List<Integer> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIds(roleIdList);
        return CommonResult.successData(user);
    }

    @ApiOperation(value = "管理员个人信息管理")
    @GetMapping("queryAdminUserInfo")
    public CommonResult queryAdminUserInfo() {
        SysUserEntity user = getUser();
        return CommonResult.successData(user);
    }


    /**
     * 保存用户
     */

    @ApiOperation(value = "保存用户")
    @PostMapping("/save")
    public CommonResult save(@RequestBody SysUserEntity user) {

        user.setCreateUserId(getUserId());
        user.setCreateTime(new Date());
        sysUserService.save(user);
        sysUserRoleService.saveOrUpdate(user.getId(), user.getRoleIds());

        return CommonResult.successMsg("ok");
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public CommonResult info() {
        Map map = new HashMap();
        map.put("user", getUser());
        return CommonResult.successData(map);
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户")
    @PostMapping("/update")
//    @RequiresPermissions("sys:user:update")
    public CommonResult update(@RequestBody SysUserEntity user) {

        user.setCreateUserId(getUserId());
        sysUserService.update(user);

        return CommonResult.successMsg("ok");
    }

    @ApiOperation(value = "修改用户")
    @PostMapping("/updateStatus")
    public CommonResult updateStatus(@RequestBody SysUserEntity user) {
        sysUserService.updateById(user);

        return CommonResult.successMsg("ok");
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    public CommonResult delete(@RequestBody Long[] userIds) {
        sysUserService.removeByIds(Arrays.asList(userIds));
        return CommonResult.successMsg("ok");
    }


    @GetMapping("data")
    public CommonResult data() {
        /**
         * /今天
         *     select * from vd_user where to_days(createTime) = to_days(now())
         *     //最近7天
         *     select * from vd_user  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(createTime);
         *     //最近一个月
         *     select * from vd_user  where DATE_SUB(CURDATE(),  INTERVAL 1 MONTH) <= date(createTime);
         *     <!-- 按日查询 -->
         *     SELECT DATE_FORMAT(created_date,'%Y-%m-%d') as time,sum(money) money FROM o_finance_detail where org_id = 1000  GROUP BY  time
         *     <!-- 按月查询 -->
         *     SELECT DATE_FORMAT(created_date,'%Y-%m') as time,sum(money)  money FROM o_finance_detail where org_id = 1000  GROUP BY  time
         *     <!-- 按年查询 -->
         *     SELECT DATE_FORMAT(created_date,'%Y') as time,sum(money)  money FROM o_finance_detail where org_id = 1000  GROUP BY  time
         *     <!-- 按周查询 -->
         *     SELECT DATE_FORMAT(created_date,'%Y-%u') as time,sum(money)  money FROM o_finance_detail where org_id = 1000  GROUP BY  time
         */
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.apply("TO_DAYS( NOW( ) ) - TO_DAYS( create_time) <= 1");
        int yesterday = sysUserService.count(queryWrapper);
        queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("to_days(create_time) = to_days(now())");
        //今天
        int dayCount = sysUserService.count(queryWrapper);
        queryWrapper = new QueryWrapper();
        //7天内
        queryWrapper.apply("DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(create_time)");
        int day7 = sysUserService.count(queryWrapper);
        queryWrapper = new QueryWrapper();
        queryWrapper.apply("DATE_SUB(CURDATE(),  INTERVAL 1 MONTH) <= date(create_time)");
        //最近一个月
        int day30 = sysUserService.count(queryWrapper);
        queryWrapper = new QueryWrapper();
        queryWrapper.apply("DATE_SUB(CURDATE(),  INTERVAL 3 MONTH) <= date(create_time)");
        //最近三个月
        int day90 = sysUserService.count(queryWrapper);
        //总数量
        int count = sysUserService.count();

        Map map = new HashMap();
        map.put("dayCount", dayCount);
        map.put("day7", day7);
        map.put("day30", day30);
        map.put("day90", day90);
        map.put("count", count);
        map.put("yesterday", yesterday);
        return CommonResult.successData(map);

    }


}
